package com.justreading.netty;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

import java.util.concurrent.TimeUnit;

/**
 * @author LYJ
 * @Description
 * @date 2021 年 10 月 27 日 下午5:00
 */
public class NettyServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        System.out.println(ctx.pipeline().channel().eventLoop().hashCode());

//        ctx.channel().eventLoop().execute(() -> {
//            try {
//                Thread.sleep(5 * 1000);
//                ctx.writeAndFlush(Unpooled.copiedBuffer("hello,客户端~()", CharsetUtil.UTF_8));
//                System.out.println("channel code = " + ctx.channel().hashCode());
//            } catch (InterruptedException e) {
//                System.out.println("发生异常" + e.getMessage());
//                e.printStackTrace();
//            }
//        });
//
//
//        ctx.channel().eventLoop().execute(() -> {
//            try {
//                TimeUnit.SECONDS.sleep(5L);
//                ctx.writeAndFlush(Unpooled.copiedBuffer("hello，客户端~2", CharsetUtil.UTF_8));
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//        });
//
//        ctx.channel().eventLoop().schedule(() -> {
//            ctx.writeAndFlush(Unpooled.copiedBuffer("hello,我是定时任务", CharsetUtil.UTF_8));
//        }, 5, TimeUnit.SECONDS);


//        System.out.println("服务器读取线程" + Thread.currentThread().getName());
//        System.out.println("server ctx = " + ctx);
//        System.out.println("看看channel和pipeline的关系");
//        Channel channel = ctx.channel();
//        ChannelPipeline pipeline = ctx.pipeline();
//
//
//        ByteBuf buf = (ByteBuf) msg;
//        System.out.println("客户端发送消息是:" + buf.toString(CharsetUtil.UTF_8));
//        System.out.println("客户端的地址是:" + channel.remoteAddress());

    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush(Unpooled.copiedBuffer("hello,客户端~（>）", CharsetUtil.UTF_8));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
